/**
 * @author selkhateeb
 */

/*
 * TODO: Features & Enhancements
 *       - Delete button
 *       - Navigation tool bar (new, delete, next, prev, edit, save, etc)
 *         see OpenBravo for more info
 */

dojo.provide("nanosn.tracfaces.ui.DataEditor");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.Form");
dojo.require("dojo.cookie");
dojo.require("dojox.data.QueryReadStore");
dojo.declare("nanosn.tracfaces.ui.DataEditor", null, 
{
    //Private Fields
    _grid: /* dojox.grid.DataGrid */ null,
    _tabContainer: /* dijit.layout.TabContainer */ null,
    _contentPaneEditor: /* dijit.layout.ContentPane */ null,
    _contentPaneDataGrid: /* dijit.layout.ContentPane */ null,
    _form: null,
    _buttonSave : null,
    
    //Public Fields
    dataStore: null,
    structure: /* dojox.grid._Layout */ null,
    url: null,
    
    /**
     * Constructor:
     * Initilizes the widgets and displays the user interface.
     * @param {Object} args
     * @param {NodeItem} node
     */
    constructor: function(args, node)
    {
/*
        if(!args.structure)
            throw new Error("Missing argument: structure");
        if(!args.url && !args.dataStore)
            throw new Error("Missing argument: url or dataStore");
*/
        dojo.mixin(this, args)

        if(args.url)
        {
            //this.dataStore = new dojo.data.ItemFileReadStore({
            this.dataStore = new dojox.data.QueryReadStore({
                url: this.url
            });
        }
		else
		{
			//Dummy mode
			this._initilizeDumyData();
		}

            
        //this._initilizeDumyData();
        if(!node)
            node = dojo.body();
        this._InitilizeWidgets(node);
    },
    
    _InitilizeWidgets: function(node)
    {
        /***********
         * this._grid
         ***********/
        gridArgs = 
        {
            query: 
            {
                id: '*'
            },
            store: this.dataStore,
            structure: this._getGridLayout()
        //rowsPerPage: 20,
        //selectionMode: 'none', 'single', 'multiple', 'extended'
        //				none: no selections can be made.
        //              single: only allows one row to be selected at a time.
        //              Multiple: allows multiple rows to be selected.
        //                        There are no keyboard modifiers: to deselect a row you click on it again.
        //              Extended(Default): allows single rows and ranges of rows to be selected.
        
        //columnReordering:(Boolean) /* column reordering using Dojo’s drag and drop architecture. */
        
        //headerMenu: (dijit.Menu) /* header context menu */
        
        
        //onClick: this._grid_onClick // Not a good idea the context of 'this' will be the grid which we dont want
        };
        this._grid = new dojox.grid.DataGrid(gridArgs, document.createElement("div"));
        dojo.connect(this._grid, "onRowDblClick", this, this._grid_onRowDblClick);
        dojo.connect(this._grid, "onSelected", this, this._grid_onSelected);

        /**************
        this._buttonSave
         **************/
        this._buttonSave = new dijit.form.Button({
            label: "Save"
        });
        dojo.connect(this._buttonSave, "onClick", this, this._buttonSave_onClick);
        /************
         * this._form
         ************/
        this._form = new dijit.form.Form({
            name: "accounts",
            action: "?date=please",
            method: "POST",
            encType: "",
            "accept-charset": "",
            accept: "",
            target: ""
        });
        this._form.domNode.appendChild(this._generateEditView());
        this._form.domNode.appendChild(this._buttonSave.domNode);
        
        /***********
         * this._tabContainer
         **********/
        this._tabContainer = new dijit.layout.TabContainer(
        {
            style: "height: 100%; width: 100%;"
        }, document.createElement("div"));
        
        /***********
         * this._contentPaneEditor
         ***********/
        this._contentPaneEditor = new dijit.layout.ContentPane(
        {
            title: "Editor",
            content: this._form
        });
        
        /***********
         * this._contentPaneDataGrid
         ***********/
        this._contentPaneDataGrid = new dijit.layout.ContentPane(
        {
            title: "Table",
            content: this._grid
        });
        
        //Start up stuff
        this._tabContainer.addChild(this._contentPaneDataGrid);
        this._tabContainer.addChild(this._contentPaneEditor);
        
        node.appendChild(this._tabContainer.domNode);
        this._tabContainer.startup();
        
    },
    
    _getGridLayout: function()
    {
        if(this.structure)
            return this.structure;
        
        var layout = [
        {
            field: "id",
            name: "Part Number",
            //width: 'auto'
			width: '100px'
        //cellType: 'dojox.grid.cells.Select',
        //options:"country,city,continent",
        //type: dojox.grid.cells.Bool,
        //editable: true
        //formatter:(function returns string) - Formats the content of this field
        //sortDesc:
        //hidden: (Boolean) - Hide the column
        },
        {
            field: "min_temp",
            name: "Minimum Temperature",
            width: "100px"
        },
        {
            field: "max_temp",
            name: "Maximum Temperature",
            width: "100px"
        },
        {
            field: "type",
            name: "Type",
            width: "100px"
        },
        {
            field: "thick",
            name: "Thickness",
            width: "5em"
        }];
        return layout;
    },
    
    _generateEditView: function()
    {
        layout = this._getGridLayout();
        label = null;
        textBox = null;
        
        formDiv = document.createElement("div");
        dojo.forEach(layout, function(item)
        {
            div = null;
            div = document.createElement("div");
            label = document.createElement("label");
            label.setAttribute("for", item.field);
            label.innerHTML = item.name + ": ";

            textBox = this._createEditBox(item);
            
            div.appendChild(label);
            div.appendChild(textBox.domNode);
            formDiv.appendChild(div);
            
        }, this);

        hidden = new dijit.form.TextBox({
            name: "__FORM_TOKEN",
            type: "hidden",
            value: dojo.cookie("trac_form_token")
        });
        formDiv.appendChild(hidden.domNode);
        
        return formDiv;
    },

    _createEditBox: function(item)
    {
        editBox = null
        if(!item.editortype)
        {
            editBox = new dijit.form.TextBox(
            {
                name: item.field
            }, div);
        }
        return editBox;
    },

    _initilizeDumyData: function()
    {
        var data = 
        {
            identifier: 'id',
            label: 'id',
            
            items: [
        
            {
                id: '4001',
                min_temp: -946,
                max_temp: 931,
                max_pres: 647,
                type: 1,
                thick: 0.25,
                inner: 0.9375,
                outer: 13.4375
            },
            {
                id: '4002',
                min_temp: -601,
                max_temp: 1894,
                max_pres: 208,
                type: 1,
                thick: 0.03125,
                inner: 4.0,
                outer: 13.75
            },
            {
                id: '4003',
                min_temp: 456,
                max_temp: 791,
                max_pres: 132,
                type: 1,
                thick: 0.125,
                inner: 2.3125,
                outer: 6.1875
            }, ]
        };
        this.dataStore = new dojo.data.ItemFileReadStore(
        {
            data: data
        });
    },
    
    _grid_onRowDblClick: function(obj)
    {
        try 
        {
            this._tabContainer.selectChild(this._contentPaneEditor);
        } 
        catch (e) 
        {
            console.error(e);
        }
        
    },
    
    _grid_onSelected: function(rowIndex)
    {
        this._fill_editor_data(rowIndex);
    },

    _buttonSave_onClick: function()
    {
        this._tabContainer.selectChild(this._contentPaneDataGrid);
        var deferred = dojo.xhrPost({
            url:'', /* other stuff, no load: */
            form: this._form.domNode
        });
        deferred.addCallback(dojo.hitch(this,"handler"));
        deferred.addErrorback(function(err){
            //TODO Display error to user
            console.log("an error.");
        });
        

    },

    handler:function(data){
        try
        {
            
            this._grid._refresh();
            

        }
        catch(e)
        {
            console.log(e)
        }
    },
    
    _fill_editor_data: function(rowIndex)
    {
        console.debug("DEBUG: nanosn.tracfaces.ui.DataEditor._fill_editor_data: param: rowIndex=[" + rowIndex + "]");

        inputCollection = dojo.query("input");
        
        item = this._grid.getItem(rowIndex).i;
        console.debug(item);
        
        inputCollection.forEach(function(inputElement)
        {
            try 
            {
                if (inputElement.name) 
                {
                    value = eval("item." + inputElement.name);
                    if (value != undefined) 
                    {
                        inputElement.value = value;
                    }
                    else 
                    {
                        error = new Error();
                        error.message = "DEBUG: nanosn.tracfaces.ui.DataEditor._fill_editor_data: " +
                        "No item exists for item." +
                        inputElement.name +
                        "\n" +
                        "inputElement.name = [" +
                        inputElement.name +
                        "] ";
                        //error. 
                        throw error;
                    }
                }
                
            } 
            catch (e) 
            {
                console.debug(e);
            }
        });
    }
});
